﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using HU8.Helpers.Base;
using HU8.Helpers.Files.Resource;
using System.Text.RegularExpressions;
using System.Security.AccessControl;

namespace HU8.Helpers.Files
{
    public class FileHelper
    {

        public static string[] TextExts = { ".txt", ".html", ".htm", ".htmlx", ".xml", ".php", ".js", ".asp", ".aspx", ".css", ".sql", ".config", ".sitemap" };
        public static string DateFormat = "yyyy-MM-dd HH:mm";
        /// <summary>
        /// 文件类型后辍字典.   chiron  2011-7-8
        /// </summary>
        public readonly static IDictionary<string, string[]> fileTypeExtension = new Dictionary<string, string[]>
        {
            {"image",new string[]{".png",".jpg","jpeg",".bmp",".gif",".svg"}},
            {"flash",new string[]{".swf"}},
            {"compressed",new string[]{".rar",".zip",".gz"}}
        };

        #region SIZE

        /// <summary>
        /// 获取文件夹的大小
        /// </summary>
        /// <param name="p">路径</param>
        /// <returns></returns>
        public static long GetDirectorySize(string p)
        {
            try
            {
                // Calculate total bytes of all files in a loop.
                long b = 0;

                // Get array of all file names.
                string[] paths = Directory.GetDirectories(p, "*.*");
                foreach (string path in paths)
                {
                    b += GetDirectorySize(path);
                }

                string[] a = Directory.GetFiles(p, "*.*");
                foreach (string name in a)
                {
                    FileInfo info = new FileInfo(name);
                    b += info.Length;
                }
                // 4
                // Return total size
                return b;
            }
            catch
            {
                return 0;
            }
        }

        /// <summary>
        /// 把文件长度翻译为大小String
        /// </summary>
        /// <param name="size"></param>
        /// <returns></returns>
        public static string SizeToString(long size)
        {
            bool isNegative = size < 0;
            size = Math.Abs(size);
            string s = size + " bytes";
            long kb = 1024;
            long mb = kb * 1024;
            long gb = mb * 1024;
            if (size > kb && size < mb)
            {
                s = (size / kb) + " KB";
            }
            else if (size >= mb && size < gb)
            {
                s = (size / mb) + " MB";
            }
            else if (size > gb)
            {
                s = (size / gb) + " GB";
            }
            if (isNegative)
            {
                s = "-" + s;
            }
            return s;
        }

        #endregion

        #region Checking
        /// <summary>
        /// 测试系统文件夹，是否可以读写
        /// </summary>
        /// <param name="folderPath"></param>
        /// <returns></returns>
        public static bool CheckSystemPath(string folderPath)
        {
            try
            {
                using (FileStream fs = new FileStream(folderPath + "\\a.txt", FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite))
                {
                    fs.Close();
                }
                if (File.Exists(folderPath + "\\a.txt"))
                {
                    System.IO.File.Delete(folderPath + "\\a.txt");
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 测试系统文件，是否可以读写
        /// </summary>
        /// <param name="filePath">一个带有systemfile.aspx的文件</param>
        /// <returns></returns>
        public static bool CheckSystemFile(string filePath)
        {
            try
            {
                if (filePath.IndexOf("systemfile.aspx") == -1 && !File.Exists(filePath)) return false;
                if (filePath.IndexOf("systemfile.aspx") != -1)  //做删除测试
                {
                    File.Delete(filePath);
                    return true;
                }
                StreamReader sr = new StreamReader(filePath);
                string content = sr.ReadToEnd();
                sr.Close();
                content += " ";
                StreamWriter sw = new StreamWriter(filePath, false);
                sw.Write(content);
                sw.Close();
                return true;
            }
            catch
            {
                return false;
            }
        }

        #endregion

        #region Creation

        /// <summary>
        /// 创建新文本文件
        /// </summary>
        /// <param name="path"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static JsonResponse CreateTextFile(string path, string fileName, bool overwrite, string preset = "")
        {
            JsonResponse response = new JsonResponse();
            string ext = Path.GetExtension(fileName);
            if (TextExts.Contains(ext))
            {
                try
                {
                    string filePath = Path.Combine(path, fileName);
                    if (!File.Exists(filePath) || overwrite)
                    {
                        StreamWriter sw = File.CreateText(filePath);
                        sw.WriteLine(preset);
                        sw.Close();
                        response.success = true;
                        response.message = string.Format("文件[{0}]创建成功", fileName);
                    }
                    else
                    {
                        response.success = false;
                        response.message = string.Format("文件创建失败：文件已经存在");
                    }
                }
                catch (Exception ex)
                {
                    response.success = false;
                    response.message = string.Format("文件创建失败：{0}", ex.Message);
                }
            }
            else
            {
                response.success = false;
                response.message = "无法创建非文本文件";
            }
            return response;
        }

        /// <summary>
        /// 创建新的文件夹
        /// </summary>
        /// <param name="path"></param>
        /// <param name="folderName"></param>
        /// <returns></returns>
        public static JsonResponse CreateFolder(string path, string folderName)
        {
            JsonResponse response = new JsonResponse();
            string folderPath = Path.Combine(path, folderName);

            if (!Directory.Exists(folderPath))
            {
                try
                {
                    Directory.CreateDirectory(folderPath);
                    response.success = true;
                    response.message = string.Format("文件夹[{0}]创建成功", folderName);
                }
                catch (Exception ex)
                {
                    response.success = false;
                    response.message = string.Format("添加文件夹失败：{0}", ex.Message);
                }
            }
            else
            {
                response.success = false;
                response.message = string.Format("添加文件夹失败：文件夹已经存在");
            }
            return response;
        }

        /// <summary>
        /// 读取文本内容
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static string ReadTextFile(string filePath)
        {
            StringBuilder sb = new StringBuilder();
            using (StreamReader objReader = new StreamReader(filePath, System.Text.Encoding.UTF8))
            {
                sb.Append(objReader.ReadToEnd());
                objReader.Close();
            }
            return sb.ToString();
        }

        /// <summary>
        /// 存储文本内容
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="content"></param>
        /// <returns></returns>
        public static JsonResponse SaveTextFile(string filePath, string content)
        {
            JsonResponse response = new JsonResponse();
            try
            {
                StreamWriter streamWriter = new StreamWriter(filePath);
                streamWriter.Write(content);
                streamWriter.Flush();
                streamWriter.Close();
                response.success = true;
                response.message = "文件保存成功";
            }
            catch (Exception ex)
            {
                response.success = false;
                response.message = string.Format("文件保存失败：{0}", ex.Message);
            }
            return response;
        }

        #endregion


        //重命名文件
        public static JsonResponse Rename(string filePath, string newName)
        {
            JsonResponse response = new JsonResponse();
            if (!String.IsNullOrEmpty(filePath) && !String.IsNullOrEmpty(newName))
            {
                if (File.Exists(filePath))
                {
                    FileInfo info = new FileInfo(filePath);
                    string newPath = filePath.Replace(info.Name, newName); //新的地址
                    if (!newName.Contains("."))
                    {
                        newPath += info.Extension; //加上ext
                    }
                    if (File.Exists(newPath))
                    {
                        response.success = false;
                        response.message = newName + "文件已经存在，请输入另一个文件名";
                    }
                    else
                    {
                        info.MoveTo(newPath);
                        response.success = true;
                        response.message = newName + "文件重命名成功";
                    }
                }
                else if (Directory.Exists(filePath))
                {
                    DirectoryInfo info = new DirectoryInfo(filePath);
                    string newPath = filePath.Replace(info.Name, newName); //新的地址
                    if (Directory.Exists(newPath))
                    {
                        response.success = false;
                        response.message = newName + "文件夹已经存在，请输入另一个文件夹名";
                    }
                    else
                    {
                        info.MoveTo(newPath);
                        response.success = true;
                        response.message = newName + "文件夹重命名成功";
                    }
                }
                else
                {
                    response.success = false;
                    response.message = "文件不存在";
                }
            }
            return response;
        }
        /// <summary>
        /// 设置文件为可读写
        /// </summary>
        /// <param name="filename"></param>
        public static void SetReadOnly(string filename)
        {
            var fileInfo = new FileInfo(filename);
            if (fileInfo.Exists)
            {
                if (fileInfo.IsReadOnly) fileInfo.IsReadOnly = false;
            }
        }

        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="filename">文件名</param>
        /// Author      Chiron
        public static void DeleteFile(string filename)
        {
            var fileInfo = new FileInfo(filename);
            if (fileInfo.Exists)
            {
                if (fileInfo.IsReadOnly) fileInfo.IsReadOnly = false;
                fileInfo.Delete();
            }
        }

        /// <summary>
        /// 删除文件夹
        /// </summary>
        /// <param name="path">文件夹路径</param>
        /// <param name="recursive">若为 true，则删除此目录、其子目录以及所有文件；否则为 false。</param>
        /// Author      Chiron
        public static void DeleteDirectory(string path, bool recursive = true)
        {
            var dir = new DirectoryInfo(path);
            if (dir.Exists)
            {
                foreach (var file in dir.GetFiles("*", SearchOption.AllDirectories).Where(d => d.IsReadOnly))
                {
                    file.IsReadOnly = false;
                }
                var dirs=dir.GetDirectories("*", SearchOption.AllDirectories).OrderByDescending(d => d.FullName);
                foreach (var d in dirs) {
                    d.Delete(recursive);
                }
                dir.Delete(recursive);
            }
        }

        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="paths"></param>
        /// <param name="recursive"></param>
        /// <returns></returns>
        public static JsonResponse DeleteFiles(string paths, bool recursive)
        {
            JsonResponse response = new JsonResponse();
            response.success = true;
            string[] files = paths.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
            if (files.Count() > 0)
            {
                foreach (string f in files)
                {
                    if (Directory.Exists(f))
                    {
                        try
                        {
                            Directory.Delete(f, recursive);
                            if (recursive)
                            {
                                response.message += string.Format("文件夹 {0} 以及其内容已经被删除<br/>", f);
                            }
                            else
                            {
                                response.message += string.Format("文件夹 {0} 已经被删除<br/>", f);
                            }
                        }
                        catch (Exception ex)
                        {
                            response.message += string.Format("文件夹 {0} 删除失败，{1}<br/>", f, ex.Message);
                            response.success = false;
                        }
                    }
                    else if (File.Exists(f))
                    {
                        try
                        {
                            File.Delete(f);
                            response.message += string.Format("{0} 已经被删除<br/>", f);
                        }
                        catch (Exception ex)
                        {
                            response.message += string.Format("文件 {0} 删除失败，{1}<br/>", f, ex.Message);
                            response.success = false;
                        }
                    }
                    else
                    {
                        response.message += string.Format("{0} 不存在<br/>", f);
                        response.success = false;
                    }
                }
            }
            else
            {
                response.message = "没有选中的文件<br/>";
                response.success = false;
            }
            return response;
        }


        /// <summary>
        /// 清理文件名，如果服务器有该文件original_name.png，则改名为：original_name(1).png 
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static string CleanFileName(string fileName)
        {
            return "";

        }



        #region Getters
        /// <summary>
        /// 获取文件夹列表
        /// </summary>
        /// <param name="currentDir">当前文件夹</param>
        /// <param name="physicalPath">物理文件夹，用来计算相对路径</param>
        /// <param name="basePath">基础相对路径，用来计算路径</param>
        /// <returns></returns>
        public static List<Folder> GetFolderList(string path, string basePath)
        {
            List<Folder> folders = new List<Folder>();
            if (Directory.Exists(path))
            {
                DirectoryInfo dir = new DirectoryInfo(path);
                DirectoryInfo[] dirs = dir.GetDirectories();
                foreach (DirectoryInfo info in dirs)
                {
                    Folder folder = new Folder(info.FullName, basePath);
                    folders.Add(folder);
                }
            }
            return folders;
        }


        /// <summary>
        /// 获取文件列表
        /// </summary>
        /// <param name="dir">当前文件夹</param>
        /// <returns></returns>
        /// chiron  changed 2011-7-8
        public static List<FolderFile> GetFileList(string path, string basePath, string type = "")
        {
            List<FolderFile> files = new List<FolderFile>();
            if (Directory.Exists(path))
            {
                DirectoryInfo dir = new DirectoryInfo(path);
                FileInfo[] fileInfos = dir.GetFiles();

                if (fileTypeExtension.Keys.Contains(type))
                {
                    var fileExt = fileTypeExtension[type];
                    foreach (FileInfo ff in fileInfos)
                    {
                        FolderFile f = new FolderFile(ff.FullName, basePath);
                        if (fileExt.Contains(f.Extension.ToLower()))
                        {
                            files.Add(f);
                        }
                    }
                }
                else
                {
                    foreach (FileInfo ff in fileInfos)
                    {
                        FolderFile f = new FolderFile(ff.FullName, basePath);
                        files.Add(f);
                    }
                }
            }
            files.OrderByDescending(f => f.Created);
            return files;
        }

        #endregion


        #region 从一个文件夹到另一个文件夹的操作
        /// <summary>
        /// 删除文件夹里面的文件
        /// </summary>
        /// <param name="folderPath"></param>
        /// <param name="exceptions"></param>
        public static JsonResponse DeleteFolderContents(string folderPath, string previousPath, string exceptions)
        {
            JsonResponse response = new JsonResponse();
            response.success = true;

            List<string> deletedFiles = new List<string>();
            List<string> deletedDirectories = new List<string>();

            DeleteFolderContents(folderPath, previousPath, exceptions, deletedFiles, deletedDirectories);

            foreach (string file in deletedFiles)
            {
                try
                {
                    File.Delete(file);
                }
                catch (Exception ex)
                {
                    response.message += ex.Message + "<br/>";
                    response.success = false;
                }
            }
            foreach (string dir in deletedDirectories)
            {
                try
                {
                    Directory.Delete(dir);
                }
                catch (Exception ex)
                {
                    response.message += ex.Message + "<br/>";
                    response.success = false;
                }
            }
            return response;
        }
        /// <summary>
        /// 清空文件夹
        /// </summary>
        /// <param name="folderPath"></param>
        /// <param name="previousPath"></param>
        /// <param name="exceptions"></param>
        /// <param name="deletedFiles"></param>
        /// <param name="deletedDirectories"></param>
        /// <returns></returns>
        public static bool DeleteFolderContents(string folderPath, string previousPath, string exceptions, List<string> deletedFiles, List<string> deletedDirectories)
        {
            bool allowDelete = true;
            DirectoryInfo di = new DirectoryInfo(folderPath);
            foreach (FileInfo fi in di.GetFiles())
            {
                string pre = previousPath + (previousPath.EndsWith("/") ? "" : "/") + fi.Name;
                if (BaseHelper.IsNotInException(pre, exceptions))
                {
                    deletedFiles.Add(fi.FullName);
                }
                else
                {
                    allowDelete = false;
                }
            }

            foreach (DirectoryInfo d in di.GetDirectories())
            {
                string pre = previousPath + (previousPath.EndsWith("/") ? "" : "/") + d.Name + "/";
                if (BaseHelper.IsNotInException(pre, exceptions))
                {
                    if (DeleteFolderContents(d.FullName, pre, exceptions, deletedFiles, deletedDirectories))
                    {
                        deletedDirectories.Add(d.FullName);
                    }
                }
                else
                {
                    allowDelete = false;
                }
            }
            return allowDelete;
        }


        /// <summary>
        /// 将文件夹里的文件拷贝到另一个文件夹
        /// </summary>
        /// <param name="folder"></param>
        /// <param name="toFolder"></param>
        /// <returns></returns>
        public static JsonResponse CopyContents(string folder, string toFolder)
        {
            return RelocateContents(folder, toFolder, false);
        }

        /// <summary>
        /// 将文件夹里的文件移动到另一个文件夹
        /// </summary>
        /// <param name="folder"></param>
        /// <param name="toFolder"></param>
        /// <returns></returns>
        public static JsonResponse CutContents(string folder, string toFolder)
        {
            return RelocateContents(folder, toFolder, true);
        }

        /// <summary>
        /// 移动或者剪切一个文件夹里的内容到另一个文件夹
        /// </summary>
        /// <param name="folder"></param>
        /// <param name="toFolder"></param>
        /// <param name="isMove"></param>
        /// <returns></returns>
        public static JsonResponse RelocateContents(string folder, string toFolder, bool isMove)
        {
            if (Directory.Exists(folder))
            {
                DirectoryInfo di = new DirectoryInfo(folder);
                List<string> fileList = new List<string>();
                foreach (FileInfo fi in di.GetFiles())
                {
                    fileList.Add(fi.FullName);
                }
                foreach (DirectoryInfo d in di.GetDirectories())
                {
                    fileList.Add(d.FullName);
                }
                return Relocate(fileList, toFolder, isMove);
            }
            else if (File.Exists(folder))
            {
                return Relocate(new List<string>() { folder }, toFolder, isMove);
            }
            JsonResponse response = new JsonResponse();
            response.success = false;
            response.message = string.Format("文件或文件夹{0}不存在", folder);
            return response;
        }
        #endregion

        #region Copy, Cut
        /// <summary>
        /// 拷贝
        /// </summary>
        /// <param name="fileList"></param>
        /// <param name="toFolder"></param>
        /// <returns></returns>
        public static JsonResponse Copy(List<string> fileList, string toFolder)
        {
            return Relocate(fileList, toFolder, false);
        }

        public static JsonResponse Copy(string files, string toFolder)
        {
            List<string> fileList = files.Split(',').ToList();
            return Copy(fileList, toFolder);
        }


        /// <summary>
        /// 剪切
        /// </summary>
        /// <param name="files"></param>
        /// <param name="toFolder"></param>
        /// <returns></returns>
        public static JsonResponse Cut(string files, string toFolder)
        {
            List<string> fileList = files.Split(',').ToList();
            return Cut(fileList, toFolder);
        }

        /// <summary>
        /// 剪切
        /// </summary>
        /// <param name="fileList"></param>
        /// <param name="toFolder"></param>
        /// <returns></returns>
        public static JsonResponse Cut(List<string> fileList, string toFolder)
        {
            return Relocate(fileList, toFolder, true);
        }

        /// <summary>
        /// 将文件/文件夹拷贝或移动到某一个地方
        /// </summary>
        /// <param name="physicalPath">源文件、文件夹物理路径</param>
        /// <param name="dest">目标文件夹 物理路径路径</param>
        /// <param name="isFile">是否为文件</param>
        /// <param name="isMove">是否移动</param>
        public static JsonResponse Relocate(List<string> fileList, string dest, bool isMove, bool overwrite = true)
        {
            if (!dest.EndsWith(Path.DirectorySeparatorChar.ToString()))
            {
                dest += Path.DirectorySeparatorChar;
            }
            JsonResponse response = new JsonResponse();
            response.success = true;
            foreach (string physicalPath in fileList)
            {
                if (File.Exists(physicalPath)) //文件
                {
                    try
                    {
                        if (isMove)
                        {
                            MoveFile(physicalPath, dest, overwrite); //移动文件
                        }
                        else
                        {
                            CopyFile(physicalPath, dest, overwrite); //拷贝文件
                        }
                    }
                    catch (Exception ex)
                    {
                        response.success = false;
                        response.message += string.Format("文件[{0}]{2}失败：{1}<br/>", physicalPath, ex.Message, isMove ? "移动" : "拷贝");
                    }
                }
                else if (Directory.Exists(physicalPath)) //文件夹
                {
                    try
                    {
                        if (isMove)
                        {
                            MoveDirectory(physicalPath, dest, overwrite); //移动文件夹
                        }
                        else
                        {
                            CopyDirectory(physicalPath, dest, overwrite); //拷贝文件夹
                        }
                    }
                    catch (Exception ex)
                    {
                        response.success = false;
                        response.message += string.Format("文件夹[{0}]{2}失败：{1}<br/>", physicalPath, ex.Message, isMove ? "移动" : "拷贝");
                    }
                }
                else
                {
                    response.success = false;
                    response.message += "文件/文件夹[" + physicalPath + "]不存在<br/>";
                }
            }
            if (response.success)
            {
                response.message = string.Format("文件/文件夹{0}成功", isMove ? "移动" : "复制");
            }
            return response;
        }


        /// <summary>
        /// 拷贝文件夹
        /// </summary>
        /// <param name="source"></param>
        /// <param name="dest"></param>
        /// <param name="overwrite"></param>
        public static void CopyDirectory(string source, string dest, bool overwrite = true)
        {
            String[] Files;
            if (!dest.EndsWith(Path.DirectorySeparatorChar.ToString()))
            {
                dest += Path.DirectorySeparatorChar;
            }
            if (!Directory.Exists(dest))
            {
                Directory.CreateDirectory(dest);
            }
            Files = Directory.GetFileSystemEntries(source);
            foreach (string element in Files)
            {
                // Sub directories
                if (Directory.Exists(element))
                {
                    CopyDirectory(element, dest + Path.GetFileName(element));
                }
                else
                {
                    File.Copy(element, dest + Path.GetFileName(element), true);
                }
            }
        }
        /// <summary>
        /// 移动文件夹
        /// </summary>
        /// <param name="source"></param>
        /// <param name="dest"></param>
        /// <param name="overwrite"></param>
        /// <returns></returns>
        public static void MoveDirectory(string source, string dest, bool overwrite)
        {
            DirectoryInfo directoryInfo = new DirectoryInfo(source);
            Directory.Move(directoryInfo.FullName, Path.Combine(dest, directoryInfo.Name));//移动到一个新的地点
        }
        /// <summary>
        /// 移动文件
        /// </summary>
        /// <param name="source"></param>
        /// <param name="dest"></param>
        /// <param name="overwrite"></param>
        public static void MoveFile(string source, string dest, bool overwrite = true)
        {
            FileInfo fileInfo = new FileInfo(source);
            File.Move(fileInfo.FullName, Path.Combine(dest, fileInfo.Name));//移动到一个新的地点
        }
        /// <summary>
        /// 拷贝文件
        /// </summary>
        /// <param name="source">原文件详细地址</param>
        /// <param name="dest">目标文件夹</param>
        /// <param name="overwrite"></param>
        public static void CopyFile(string source, string dest, bool overwrite = true)
        {
            FileInfo fileInfo = new FileInfo(source);
            File.Copy(fileInfo.FullName, Path.Combine(dest, fileInfo.Name), overwrite);//移动到一个新的地点
        }
        /// <summary>
        /// 拷贝文件
        /// </summary>
        /// <param name="source">原文件详细地址</param>
        /// <param name="newName">新文件详细地址</param>
        /// <param name="overwrite"></param>
        public static void CopyFile1(string source, string newName, bool overwrite = true)
        {
            FileInfo fileInfo = new FileInfo(source);
            File.Copy(fileInfo.FullName, newName, overwrite);//移动到一个新的地点
        }

        #endregion

        #region 属性操作
        /// <summary>
        /// 设置文件的标记，只读，系统文件，等
        /// </summary>
        /// <param name="path"></param>
        /// <param name="isReadOnly">只读</param>
        /// <param name="isHidden">隐藏</param>
        /// <param name="isSystem">系统文件</param>
        /// <param name="isAchive">索引</param>
        public static JsonResponse SetFileAttributes(string path, bool isReadOnly, bool isHidden, bool isSystem, bool isAchive, bool isWritable, bool isBrowsable)
        {
            JsonResponse response = new JsonResponse();
            try
            {
                SetAttribute(path, FileAttributes.ReadOnly, isReadOnly);
                SetAttribute(path, FileAttributes.Hidden, isHidden);
                SetAttribute(path, FileAttributes.System, isSystem);
                SetAttribute(path, FileAttributes.Archive, isAchive);
                SetPermission(path, isWritable, isBrowsable);
                response.success = true;
                response.message = string.Format("文件[{0}]属性设置成功", path);
            }
            catch (Exception ex)
            {
                response.success = false;
                response.message = string.Format("文件[{0}]属性设置失败", ex.Message);
            }
            return response;
        }

        /// <summary>
        /// 设置文件夹标记
        /// </summary>
        /// <param name="path"></param>
        /// <param name="isReadOnly">只读</param>
        /// <param name="isHidden">隐藏</param>
        /// <param name="isSystem">系统文件</param>
        /// <param name="isAchive">索引</param>
        /// <param name="recursive">是否应用于子文件以及文件夹</param>
        public static JsonResponse SetFolderAttributes(string path, bool isReadOnly, bool isHidden, bool isSystem, bool isAchive, bool isWritable, bool isBrowsable, bool recursive)
        {
            JsonResponse response = new JsonResponse();
            try
            {
                SetAttribute(path, FileAttributes.ReadOnly, isReadOnly);
                SetAttribute(path, FileAttributes.Hidden, isHidden);
                SetAttribute(path, FileAttributes.System, isSystem);
                SetAttribute(path, FileAttributes.Archive, isAchive);
                SetPermission(path, isWritable, isBrowsable);
                if (recursive)
                {
                    DirectoryInfo di = new DirectoryInfo(path);
                    foreach (DirectoryInfo d in di.GetDirectories())
                    {
                        SetFolderAttributes(d.FullName, isReadOnly, isHidden, isSystem, isAchive, isWritable, isBrowsable, recursive);
                    }
                    foreach (FileInfo f in di.GetFiles())
                    {
                        SetFileAttributes(f.FullName, isReadOnly, isHidden, isSystem, isAchive, isWritable, isBrowsable);
                    }
                }
                response.success = true;
                response.message = string.Format("文件夹[{0}]属性设置成功", path);
            }
            catch (Exception ex)
            {
                response.success = false;
                response.message = string.Format("文件夹[{0}]属性设置失败", ex.Message);
            }
            return response;
        }

        /// <summary>
        /// 设定当前Asp.Net用户可以写目录
        /// </summary>
        /// <param name="path"></param>
        /// <param name="isTrue"></param>
        /// <param name="userName"></param>
        public static void SetPermission(string path, bool isWritable, bool isReadable)
        {
            string account = (string.IsNullOrEmpty(Environment.UserDomainName) ? "" : Environment.UserDomainName + "\\") + Environment.UserName;
            FileSystemRights rights = FileSystemRights.Read;
            if (isWritable)
            {
                rights = FileSystemRights.ReadAndExecute | FileSystemRights.Modify | FileSystemRights.Synchronize;
            }
            else
            {
                if (isReadable)
                {
                    rights = FileSystemRights.ReadAndExecute | FileSystemRights.Synchronize;
                }
            }
            SetSecurityRule(path, account, rights, AccessControlType.Allow);
        }

        public static void AddSecurityRule(string filePath, string account, FileSystemRights rights, AccessControlType controlType)
        {
            FileSystemSecurity fSecurity;
            if (File.Exists(filePath))
            {
                fSecurity = File.GetAccessControl(filePath);
            }
            else
            {
                fSecurity = Directory.GetAccessControl(filePath);
            }
            fSecurity.AddAccessRule(new FileSystemAccessRule(account, rights, controlType));
            if (File.Exists(filePath))
            {
                File.SetAccessControl(filePath, (FileSecurity)fSecurity);
            }
            else
            {
                Directory.SetAccessControl(filePath, (DirectorySecurity)fSecurity);
            }
        }

        public static void SetSecurityRule(string filePath, string account, FileSystemRights rights, AccessControlType controlType)
        {
            FileSystemSecurity fSecurity;
            if (File.Exists(filePath))
            {
                fSecurity = File.GetAccessControl(filePath);
            }
            else
            {
                fSecurity = Directory.GetAccessControl(filePath);
            }

            fSecurity.ResetAccessRule(new FileSystemAccessRule(account, rights, controlType));
            if (File.Exists(filePath))
            {
                File.SetAccessControl(filePath, (FileSecurity)fSecurity);
            }
            else
            {
                Directory.SetAccessControl(filePath, (DirectorySecurity)fSecurity);
            }
        }

        /// <summary>
        /// 设置属性
        /// </summary>
        /// <param name="path"></param>
        /// <param name="attr"></param>
        /// <param name="isTrue"></param>
        private static void SetAttribute(string path, FileAttributes attr, bool isTrue)
        {
            FileAttributes attributes = File.GetAttributes(path);

            if ((attributes & attr) == attr && !isTrue)
            {
                //删除
                attributes = RemoveAttribute(attributes, attr);
                File.SetAttributes(path, attributes);
            }
            else if (isTrue)
            {
                //添加
                File.SetAttributes(path, File.GetAttributes(path) | attr);
            }
            //不做事情
        }

        /// <summary>
        /// 去除属性
        /// </summary>
        /// <param name="attributes"></param>
        /// <param name="attributesToRemove"></param>
        /// <returns></returns>
        private static FileAttributes RemoveAttribute(FileAttributes attributes, FileAttributes attributesToRemove)
        {
            return attributes & ~attributesToRemove;
        }



        #endregion

        /// <summary>
        /// 修复文件名
        /// </summary>
        /// <param name="path"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static string FixFileName(string path, string fileName)
        {
            fileName = new Regex(@"[/\\~%]+").Replace(fileName, string.Empty);
            string thePath = Path.Combine(path, fileName);
            string ext = Path.GetExtension(fileName);
            string name = Path.GetFileNameWithoutExtension(fileName);
            int count = 1;
            while (File.Exists(Path.Combine(path, fileName)))
            {
                fileName = name + "-" + count + ext;
                count++;
            }
            return fileName;
        }
    }
}
